import fs from "fs";
import multer from "multer";
import express from "express";
import { PrismaClient, Prisma } from "@prisma/client";
import { CreateId, Check, Result, Time } from "@/utils";

const prisma = new PrismaClient();
const router = express.Router();

/** 文件列表 */
type MulterFile = Express.Multer.File;

const storage = multer.diskStorage({
   filename(req, file, callback) {
      callback(null, Time.Format(Time.Now(), "YYYY-MM-DDTHH'mm'ss") + "_" + file.originalname);
   },
   destination(req, file, callback) {
      callback(null, process.env.UPLOAD_PATH || "upload/");
   }
});

const upload = multer({ storage }).any();

/** 创建商户 */
router.post("/create", upload, async (req, res) => {
   const { name, code, apiv2, apiv3, serial_no }: Merchant.Create = req.body;
   if (!Check.Required([name, code, apiv2, apiv3, serial_no])) return res.send(Result.Error("参数错误"));

   /** 检测文件是否存在 */
   const files: MulterFile[] = (req.files as any) || [];
   if (files.length != 2) return res.send(Result.Error("参数错误"));

   const cert = files.find(item => item.fieldname == "cert");
   const certKey = files.find(item => item.fieldname == "cert_key");

   if (!cert || !certKey) return res.send(Result.Error("参数错误"));

   const { userId } = req;
   const id = await CreateId.One("mp_merchant");
   await prisma.mp_merchant.create({
      data: {
         id,
         name,
         code,
         apiv2,
         apiv3,
         serial_no,
         cert: cert.path,
         cert_key: certKey.path,
         created_by: userId,
         created_time: Time.Now()
      }
   });

   res.send(Result.OK());
});

/** 删除商户 */
router.post("/delete", async (req, res) => {
   const { id }: Merchant.Delete = req.body;

   const value = await prisma.mp_merchant.delete({ where: { id } });

   fs.unlinkSync(value.cert);
   fs.unlinkSync(value.cert_key);

   res.send(Result.OK());
});

/** 修改商户 */
router.post("/update", upload, async (req, res) => {
   const { id, name, code, apiv2, apiv3, status, serial_no }: Merchant.Update = req.body;
   if (!Check.Required([id, name, code, apiv2, apiv3, status, serial_no])) return res.send(Result.Error("参数错误"));
   const oldValue = await prisma.mp_merchant.findUnique({ where: { id } });
   if (!oldValue) return res.send(Result.Error("参数错误"));

   /** 检测文件是否存在 */
   const files: MulterFile[] = (req.files as any) || [];

   const cert = files.find(item => item.fieldname == "cert");
   const certKey = files.find(item => item.fieldname == "cert_key");

   const { userId } = req;
   await prisma.mp_merchant.update({
      where: { id },
      data: {
         name: name || oldValue.name,
         code: code || oldValue.code,
         apiv2: apiv2 == "******" ? oldValue.apiv2 : apiv2 || oldValue.apiv2,
         apiv3: apiv3 == "******" ? oldValue.apiv3 : apiv3 || oldValue.apiv3,
         serial_no: serial_no == "******" ? oldValue.serial_no : serial_no || oldValue.serial_no,
         cert: cert?.path || oldValue.cert,
         cert_key: certKey?.path || oldValue.cert_key,
         status: status || oldValue.status,
         updated_by: userId,
         updated_time: Time.Now()
      }
   });

   res.send(Result.OK());
});

/** 查看商户列表 */
router.get("/search", async (req, res) => {
   const { name, status }: Merchant.Search = req.query as any;

   const where: Prisma.mp_merchantWhereInput = {
      AND: [!!name ? { name } : {}, !!status ? { status: status } : {}]
   };

   const list = await prisma.mp_merchant.findMany({
      where,
      select: {
         id: true,
         name: true,
         code: true,
         cert: true,
         cert_key: true,
         status: true
      }
   });

   const newlist = list.map(item => {
      return {
         ...item,
         cert: item.cert.slice(31),
         cert_key: item.cert_key.slice(31),
         apiv2: "******",
         apiv3: "******",
         serial_no: "******"
      };
   });

   res.send(Result.OK(newlist));
});

// TODO 下载密钥文件
/** 下载文件 */
router.post("/download", async (req, res) => {});

export const merchant = router;
